package com.onepiece.feign.config;

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义的feign请求、响应的消息转换器代理
 * @author guoyanjiang
 * @date 2019-09-10
 */
@Service
public class FeignHttpMessageConverterDelegate {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    private HttpMessageConverters feignHttpMessageConverters;

    @PostConstruct
    public void init() {
        feignHttpMessageConverters = createFeignHttpMessageConverters();
    }

    public HttpMessageConverters getFeignHttpMessageConverters() {
        return feignHttpMessageConverters;
    }

    private HttpMessageConverters createFeignHttpMessageConverters(){
        //去掉可能存在的FastJsonHttpMessageConverter
        List<HttpMessageConverter<?>> originalMessageConverters = messageConverters.getObject().getConverters()
                .stream()
                .filter(item -> !FastJsonHttpMessageConverter.class.isInstance(item))
                .collect(Collectors.toList());
        //创建自己需要的转换器
        HttpMessageConverter feignFastJsonHttpMessageConverter = createFastJsonHttpMessageConverter();
        originalMessageConverters.add(0, feignFastJsonHttpMessageConverter);
        HttpMessageConverters converters = new HttpMessageConverters(originalMessageConverters);
        return converters;
    }

    public HttpMessageConverter createFastJsonHttpMessageConverter(SerializerFeature... serializerFeatures) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        SerializeConfig serializeConfig = SerializeConfig.getGlobalInstance();
        serializeConfig.propertyNamingStrategy = com.alibaba.fastjson.PropertyNamingStrategy.SnakeCase;
        config.setSerializeConfig(serializeConfig);
        config.setSerializerFeatures(serializerFeatures);
        converter.setFastJsonConfig(config);
        converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
        return converter;
    }
}
